/**
 * 报表保存和加载工具函数
 */

/**
 * 保存报表到本地存储
 * @param {Object} reportConfig - 报表配置
 * @param {string} name - 报表名称
 * @returns {string} 报表ID
 */
export function saveReport(reportConfig, name) {
  const reportId = `report_${Date.now()}`
  const report = {
    id: reportId,
    name: name || '未命名报表',
    config: reportConfig,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString()
  }
  
  // 获取已保存的报表
  const savedReports = getSavedReports()
  savedReports.push(report)
  
  // 保存到本地存储
  localStorage.setItem('powerbi_reports', JSON.stringify(savedReports))
  
  return reportId
}

/**
 * 更新已保存的报表
 * @param {string} reportId - 报表ID
 * @param {Object} reportConfig - 报表配置
 * @param {string} name - 报表名称
 */
export function updateReport(reportId, reportConfig, name) {
  const savedReports = getSavedReports()
  const reportIndex = savedReports.findIndex(r => r.id === reportId)
  
  if (reportIndex !== -1) {
    savedReports[reportIndex] = {
      ...savedReports[reportIndex],
      name: name || savedReports[reportIndex].name,
      config: reportConfig,
      updatedAt: new Date().toISOString()
    }
    
    localStorage.setItem('powerbi_reports', JSON.stringify(savedReports))
  }
}

/**
 * 加载报表
 * @param {string} reportId - 报表ID
 * @returns {Object|null} 报表配置
 */
export function loadReport(reportId) {
  const savedReports = getSavedReports()
  const report = savedReports.find(r => r.id === reportId)
  return report || null
}

/**
 * 删除报表
 * @param {string} reportId - 报表ID
 */
export function deleteReport(reportId) {
  const savedReports = getSavedReports()
  const filteredReports = savedReports.filter(r => r.id !== reportId)
  localStorage.setItem('powerbi_reports', JSON.stringify(filteredReports))
}

/**
 * 获取所有已保存的报表
 * @returns {Array} 报表列表
 */
export function getSavedReports() {
  try {
    const reports = localStorage.getItem('powerbi_reports')
    return reports ? JSON.parse(reports) : []
  } catch (error) {
    console.error('获取报表列表失败:', error)
    return []
  }
}

/**
 * 复制报表
 * @param {string} reportId - 源报表ID
 * @param {string} newName - 新报表名称
 * @returns {string} 新报表ID
 */
export function duplicateReport(reportId, newName) {
  const sourceReport = loadReport(reportId)
  if (!sourceReport) return null
  
  const newReportId = `report_${Date.now()}`
  const newReport = {
    id: newReportId,
    name: newName || `${sourceReport.name} - 副本`,
    config: JSON.parse(JSON.stringify(sourceReport.config)), // 深拷贝
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString()
  }
  
  const savedReports = getSavedReports()
  savedReports.push(newReport)
  localStorage.setItem('powerbi_reports', JSON.stringify(savedReports))
  
  return newReportId
}

/**
 * 导出报表为JSON文件
 * @param {string} reportId - 报表ID
 */
export function exportReportAsJSON(reportId) {
  const report = loadReport(reportId)
  if (!report) return
  
  const exportData = {
    version: '1.0',
    exportTime: new Date().toISOString(),
    report: report
  }
  
  const jsonString = JSON.stringify(exportData, null, 2)
  const blob = new Blob([jsonString], { type: 'application/json' })
  
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = `${report.name}.json`
  link.style.display = 'none'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(link.href)
}

/**
 * 从JSON文件导入报表
 * @param {File} file - JSON文件
 * @returns {Promise<string>} 导入的报表ID
 */
export function importReportFromJSON(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    
    reader.onload = (e) => {
      try {
        const importData = JSON.parse(e.target.result)
        
        if (!importData.report || !importData.report.config) {
          throw new Error('无效的报表文件格式')
        }
        
        const reportId = saveReport(
          importData.report.config,
          `${importData.report.name} - 导入`
        )
        
        resolve(reportId)
      } catch (error) {
        reject(error)
      }
    }
    
    reader.onerror = () => {
      reject(new Error('文件读取失败'))
    }
    
    reader.readAsText(file)
  })
}

/**
 * 获取报表统计信息
 * @returns {Object} 统计信息
 */
export function getReportStats() {
  const reports = getSavedReports()
  
  return {
    totalReports: reports.length,
    totalVisualizations: reports.reduce((sum, report) => {
      return sum + (report.config.visualizations?.length || 0)
    }, 0),
    lastModified: reports.length > 0 
      ? Math.max(...reports.map(r => new Date(r.updatedAt).getTime()))
      : null,
    storageSize: new Blob([localStorage.getItem('powerbi_reports') || '']).size
  }
}

/**
 * 清理过期报表
 * @param {number} daysOld - 保留天数
 */
export function cleanupOldReports(daysOld = 30) {
  const reports = getSavedReports()
  const cutoffDate = new Date()
  cutoffDate.setDate(cutoffDate.getDate() - daysOld)
  
  const filteredReports = reports.filter(report => {
    return new Date(report.updatedAt) > cutoffDate
  })
  
  localStorage.setItem('powerbi_reports', JSON.stringify(filteredReports))
  
  return reports.length - filteredReports.length // 返回清理的数量
}

/**
 * 搜索报表
 * @param {string} keyword - 搜索关键词
 * @returns {Array} 匹配的报表列表
 */
export function searchReports(keyword) {
  const reports = getSavedReports()
  
  if (!keyword) return reports
  
  const lowerKeyword = keyword.toLowerCase()
  
  return reports.filter(report => {
    return report.name.toLowerCase().includes(lowerKeyword) ||
           (report.config.description && 
            report.config.description.toLowerCase().includes(lowerKeyword))
  })
}

/**
 * 验证报表配置
 * @param {Object} config - 报表配置
 * @returns {Object} 验证结果
 */
export function validateReportConfig(config) {
  const errors = []
  const warnings = []
  
  // 检查必需字段
  if (!config.title) {
    warnings.push('报表缺少标题')
  }
  
  if (!config.visualizations || config.visualizations.length === 0) {
    warnings.push('报表没有可视化组件')
  }
  
  // 检查可视化组件
  if (config.visualizations) {
    config.visualizations.forEach((viz, index) => {
      if (!viz.type) {
        errors.push(`可视化组件 ${index + 1} 缺少类型`)
      }
      
      if (!viz.title) {
        warnings.push(`可视化组件 ${index + 1} 缺少标题`)
      }
      
      // 检查图表配置
      if (viz.type === 'bar' || viz.type === 'line') {
        if (!viz.config.xField || !viz.config.yField) {
          errors.push(`${viz.title || '图表'} 缺少必要的字段配置`)
        }
      }
      
      if (viz.type === 'pie') {
        if (!viz.config.labelField || !viz.config.valueField) {
          errors.push(`${viz.title || '饼图'} 缺少必要的字段配置`)
        }
      }
    })
  }
  
  return {
    isValid: errors.length === 0,
    errors,
    warnings
  }
}

